package com.lire.shop.controller;

import com.fasterxml.jackson.databind.util.JSONPObject;
import com.google.gson.Gson;
import com.lire.shop.converter.UserConverter;
import com.lire.shop.dao.SessionLoginRepository;
import com.lire.shop.dao.UserRepository;
import com.lire.shop.data.Constants;
import com.lire.shop.data.NullObjects;
import com.lire.shop.entity.SessionLogin;
import com.lire.shop.entity.User;
import com.lire.shop.model.vo.UserVO;
import com.lire.shop.service.WalletService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.media.Content;
import io.swagger.v3.oas.annotations.media.Schema;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.annotations.responses.ApiResponses;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.math.BigDecimal;
import java.time.Instant;
import java.util.*;


@Tag(name = "user", description = "This is a tag of user.")
@RestController
public class UserController {

    @Autowired
    private Gson gson;
    @Autowired
    private UserRepository userRepository;

    @Autowired
    private UserConverter userConverter;

    @Autowired
    private WalletService walletService;

    @Autowired
    private SessionLoginRepository sessionLoginRepository;

    @Operation(summary = "登录默认账号!!!", tags = {"user","01-test"})
    @GetMapping("/user/login/default")
    public String defaultLogin(HttpSession session){
        User user = (User) session.getAttribute(Constants.CURRENT_USER);
        if (Objects.isNull(user)) {
            user = new User();
            user.setUsername("lire-1");
            user.setPassword("password-1");
            session.setAttribute(Constants.CURRENT_USER, user);
        }
        return gson.toJson(user);
    }

    @GetMapping("/user/login")
    public String doLogin(String username, String password, HttpSession session) {
        User user = userRepository.findByUsername(username).orElseGet(NullObjects::getUser);
        if (Objects.isNull(user)) return "user need to sign up";
        session.setAttribute("user", user);
        Instant startTime = Instant.now();
        Instant limitTime = startTime.plusMillis(24 * 60 * 60 * 1000);
        SessionLogin sessionLogin = new SessionLogin();
        sessionLogin.setUsername(user.getUsername());
        sessionLogin.setStartTime(startTime.toEpochMilli());
        sessionLogin.setLimitTime(limitTime.toEpochMilli());
        sessionLoginRepository.save(sessionLogin);
        return "login...";
    }

    @GetMapping("/user/logout")
    public String doLogout(HttpSession session) {
        session.setAttribute("user", null);
        return "user is logout";
    }


    @Operation(summary = "查看当前用户", tags = {"user","01-test"})
    @GetMapping("/user")
    public String getUser(HttpSession session) {
        User curUser = (User) session.getAttribute(Constants.CURRENT_USER);
        String username = curUser.getUsername();
        User user = userRepository.findByUsername(username).orElseGet(NullObjects::getUser);
        Map<String,Object> map=new HashMap<>();
        UserVO userVO = userConverter.do2vo(user);
        map.put("user", userVO);
        return new Gson().toJson(map);
    }


    @Operation(summary = "list all user", tags = {"user"})
    @ApiResponses({
            @ApiResponse(responseCode = "200"
                    , content = {@Content(schema = @Schema(implementation = User.class), mediaType = "application/json")})
            , @ApiResponse(responseCode = "404"
            , content = @Content(schema = @Schema(implementation = User.class)))
    })

    @GetMapping("/users")
    public String getUsers() {
        List<User> user = userRepository.findAll();
        return new Gson().toJson(user);
    }

    @Operation(summary = "查询用户钱包余额", tags = {"user"})
    @GetMapping("/user/wallet/balance")
    public String getUserBalance(HttpSession session) {

        User curUser = (User) session.getAttribute("user");
        String username = curUser.getUsername();
        User user = userRepository.findByUsername(username).orElseGet(NullObjects::getUser);

        Long wid = user.getWid();
        BigDecimal balances = walletService.getBalances(wid);
        Gson gson = new Gson();

        Map<String, String> map = new HashMap<>();

        map.put("username", user.getUsername());
        map.put("balances", balances.toString());

        return gson.toJson(map);
    }
}
